﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace WickedFlame.VecDraw.Base.Controls
{
    public class ImageTextButton : Button
    {
        static ImageTextButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageTextButton), new FrameworkPropertyMetadata(typeof(ImageTextButton)));
        }

        public ImageTextButton()
        {
        }

        public object Icon
        {
            get { return (object)GetValue(IconProperty); }
            set { SetValue(IconProperty, value); }
        }

        public static readonly DependencyProperty IconProperty =
            DependencyProperty.Register("Icon", typeof(object), typeof(ImageTextButton),
            new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerce_Icon)));

        private static object OnCoerce_Icon(DependencyObject o, object value)
        {
            if (value is string)
            {
                Uri iconUri;
                // try to resolve given value as an absolute URI
                if (Uri.TryCreate(value as String, UriKind.RelativeOrAbsolute, out iconUri))
                {
                    ImageSource img = new BitmapImage(iconUri);
                    if (null != img)
                    {
                        Image icon = (o as ImageTextButton).Icon as Image;
                        if (null == icon)
                            icon = new Image();

                        icon.Source = img;
                        icon.Stretch = Stretch.None;
                        icon.SnapsToDevicePixels = true;

                        return icon;
                    }
                }
            }
            return value;
        }

        public string ButtonText
        {
            get
            {
                return (string)GetValue(ButtonTextProperty);
            }
            set
            {
                SetValue(ButtonTextProperty, value);
            }
        }

        public static readonly DependencyProperty ButtonTextProperty =
            DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageTextButton), new PropertyMetadata(""));

        public string Title
        {
            get
            {
                return (string)GetValue(TitleProperty);
            }
            set
            {
                SetValue(TitleProperty, value);
            }
        }

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(ImageTextButton), new PropertyMetadata(""));
    }
}
